import hStorage from './hStorage'
import { getUserInfo } from '../api/login'
import Vue from 'vue'
import config from '../../config/envDefault'
import extendTagConfig from '../../config/extendTag'
//图片资源的压缩集合，例：cq40w20  即图片压缩质量到原图的40% 缩放到原图的20%
const compressLevelMap = new Map([
  // 为-1时，将统一走全站webp方案
  [-1, ''],
  // 为0时，获取cdn原图
  [0, '?x-image-process=cq100w100'],
  // [1, '/cq40w20'],
  // [2, '/cq40w40'],
  // [3, '/cq40w60'],
  // [4, '/cq40w80'],
  // [5, '/cq40w100'],
  // [6, '/cq60w20'],
  // [7, '/cq60w40'],
  // [8, '/cq60w60'],
  // [9, '/cq60w80'],
  // [10, '/cq60w100'],
  // [11, '/cq80w20'],
  // [12, '/cq80w40'],
  // [13, '/cq80w60'],
  // [14, '/cq80w80'],
  // [15, '/cq80w100'],
  // [16, '/cq100w20'],
  // [17, '/cq100w40'],
  // [18, '/cq100w60'],
  // [19, '/cq100w80'],
  // 此处将用“?x-image-process=cq100w100”替换“/cq100w100”获取原图
  [20, '?x-image-process=cq100w100']
])
const tool = {
  /**
   * @description: 全局localStorage缓存封装
   */
  storage: hStorage,
  /**
   * @description: 获取数据类型
   * @param {any} o 传入一个js对象
   * @return {string} 返回一个数据类型（string,number,object,array等）
   */
  getType(o) {
    return Object.prototype.toString
      .call(o)
      .toLowerCase()
      .replace(/[\[\]]/g, '')
      .split(' ')[1]
  },
  // 判断是数组且有长度
  isArrAndLen(arr) {
    // 判断是数组且有长度
    return !!(Array.isArray(arr) && arr.length)
  },
  /**
   * 深度拷贝函数.
   * @author HuBin
   * @datetime 2022年3月14日09:42:30
   * @param {any} o - 传入一个任意的类型数据.
   * @returns {string} - 返回一个字符串.
   */
  deepCopy(o) {
    let copy = Array.isArray(o) ? [] : {}
    let _traverse = function(subO, subCopy) {
      for (var x in subO) {
        let subItem = subO[x]
        if (subItem && typeof subItem === 'object') {
          subCopy[x] = Array.isArray(subO[x]) ? [] : {}
          _traverse(subItem, subCopy[x])
        } else {
          subCopy[x] = subO[x]
        }
      }
    }
    _traverse(o, copy)
    return copy
  },
  /**
   * 判断对象.
   * @author HuBin
   * @datetime 2022-03-08 14:39:00
   * @param {any} o - 传入对象.
   * @returns {boolean} - 返回一个布尔值.
   */
  isObject(o) {
    return Object.prototype.toString.call(o) === '[object Object]'
  },
  /**
   * 判断数组.
   * @author HuBin
   * @datetime 2022-03-08 14:39:00
   * @param {any} o - 传入对象.
   * @returns {boolean} - 返回一个布尔值.
   */
  isArray(o) {
    return Object.prototype.toString.call(o) === '[object Array]'
  },
  /**
   * 补零函数.
   * @author HuBin
   * @datetime 2022-03-08 14:39:00
   * @param {number} num - 需要补零的数字.
   * @returns {string} - 返回一个补零后的字符串.
   */
  padZero(num) {
    let reg = /^\d+$/

    if (!reg.test(num)) {
      throw new Error('请输入一个整数')
    }
    return num < 10 ? '0' + num : String(num)
  },
  /**
   * @description: 时间字符串转毫秒时间戳
   * @param {String} timeStr 时间字符串
   * @return {Number} 返回一个毫秒时间戳
   */
  timestrToTimestamps(timeStr) {
    if (typeof timeStr !== 'string') {
      return null
    }
    timeStr = timeStr.replace(/-/g, '/')
    return new Date(timeStr).getTime()
  },
  /**
   * @description: 判断日期是否为昨天
   * @param {String} timeStr 时间字符串
   * @return {Boolean}
   */
  isYesterday(timeStr) {
    let todayStr = this.dateFormat('Y-m-d 12:00:00', Date.now())
    let todayMsecs = this.timestrToTimestamps(todayStr)
    let yesterdayMsecs = todayMsecs - 24 * 3600 * 1000
    let yesterdayStr = this.dateFormat('Y-m-d', yesterdayMsecs)
    let judgeTimeStr = this.dateFormat('Y-m-d', this.timestrToTimestamps(timeStr))
    return yesterdayStr === judgeTimeStr
  },
  /**
   * @description: 判断日期是否为今天
   * @param {String} timeStr 时间字符串
   * @return {Boolean}
   */
  isToday(timeStr) {
    let todayStr = this.dateFormat('Y-m-d', Date.now())
    let judgeTimeStr = this.dateFormat('Y-m-d', this.timestrToTimestamps(timeStr))
    return todayStr === judgeTimeStr
  },
  /**
   * @description: 判断日期是否为明天
   * @param {String} timeStr 时间字符串
   * @return {Boolean}
   */
  isTomorrow(timeStr) {
    let todayStr = this.dateFormat('Y-m-d 12:00:00', Date.now())
    let todayMsecs = this.timestrToTimestamps(todayStr)
    let tomorrowMsecs = todayMsecs + 24 * 3600 * 1000
    let tomorrowStr = this.dateFormat('Y-m-d', tomorrowMsecs)
    let judgeTimeStr = this.dateFormat('Y-m-d', this.timestrToTimestamps(timeStr))
    return tomorrowStr === judgeTimeStr
  },
  /**
   * @description: 判断日期是否为后天
   * @param {String} timeStr 时间字符串
   * @return {Boolean}
   */
  isDayAfterTomorrow(timeStr) {
    let todayStr = this.dateFormat('Y-m-d 12:00:00', Date.now())
    let todayMsecs = this.timestrToTimestamps(todayStr)
    let dayAfterTomorrowMsecs = todayMsecs + 48 * 3600 * 1000
    let dayAfterTomorrowStr = this.dateFormat('Y-m-d', dayAfterTomorrowMsecs)
    let judgeTimeStr = this.dateFormat('Y-m-d', this.timestrToTimestamps(timeStr))
    return dayAfterTomorrowStr === judgeTimeStr
  },
  /**
   * @description: 时间日期格式化函数
   * @param {String} format 'Y-m-d H:i:s'
   * @param {Number|String|Date} msecs 毫秒时间戳
   * @return {String} 返回一个格式化后的时间字符串
   */
  dateFormat(format, msecs) {
    if (typeof format !== 'string' || !format) {
      return null
    }
    if (arguments.length < 2) {
      return null
    }
    // 私有函数：补零函数
    const _padZero = function(num) {
      return num < 10 ? '0' + num : '' + num
    }
    let dateObj
    let isIntNumber = /^\d+$/.test(msecs)
    let isDate = Object.prototype.toString.call(msecs) === '[object Date]'
    // 毫秒时间戳必须全部为数字，或参数可传入日期对象
    if (!isIntNumber && !isDate) {
      return null
    }
    dateObj = isIntNumber ? new Date(msecs) : isDate ? msecs : ''
    // 为日期对象，才向下继续执行
    if (!dateObj) {
      return null
    }
    const year = dateObj.getFullYear()
    const month = dateObj.getMonth() + 1
    const date = dateObj.getDate()
    const hour = dateObj.getHours()
    const min = dateObj.getMinutes()
    const sec = dateObj.getSeconds()
    const oDate = { year, month, date, hour, min, sec }

    const allKeys = 'month,date,hour,min,sec'
    allKeys.split(',').forEach(key => {
      oDate['fix' + key[0].toUpperCase() + key.slice(1)] = _padZero(oDate[key])
    })
    const regArr = [
      {
        key: /Y/g,
        value: oDate.year
      },
      {
        key: /M/g,
        value: oDate.month
      },
      {
        key: /D/g,
        value: oDate.date
      },
      {
        key: /h/g,
        value: oDate.hour
      },
      {
        key: /I/g,
        value: oDate.min
      },
      {
        key: /S/g,
        value: oDate.sec
      },
      {
        key: /m/g, // 小于10，补零
        value: oDate.fixMonth
      },
      {
        key: /d/g, // 小于10，补零
        value: oDate.fixDate
      },
      {
        key: /H/g, // 小于10，补零
        value: oDate.fixHour
      },
      {
        key: /i/g, // 小于10，补零
        value: oDate.fixMin
      },
      {
        key: /s/g, // 小于10，补零
        value: oDate.fixSec
      }
    ]
    regArr.forEach(item => {
      const { key, value } = item
      format = format.replace(key, value)
    })
    return format
  },
  /**
   * 适配图片地址为cdn地址.
   * @author HuBin
   * @datetime 2022-03-10 16:15:00
   * @param {string} url - 图片地址.
   * @returns {string} - 返回一个字符串.
   */
  parseResourceUrl(url = '', compressLevel = -1) {
    if (typeof url !== 'string' || !url || url.includes('data:image/')) return url
    let arr = ['http', 'https', '//']
    let cdnDomain = config.cdnDomain
    let find = arr.some(item => url.includes(item))
    url = find ? url : cdnDomain + url
    //在https域名下，请求的资源必须是https或者跟随协议的
    url = url.replace('http:', '').replace(/https?\:\/\/admin\.zlketang\.com/g, '//image.zlketang.com')
    //给图片加上压缩
    let compressStr = compressLevelMap.has(compressLevel) ? compressLevelMap.get(compressLevel) : ''
    return (url += compressStr)
  },
  /**
   * 适配图片地址为cdn地址-数组版.
   * @author FanJingYang
   * @datetime 2023年6月16日 10:17:56
   * @param {array}  - 图片数组.
   * @returns {array} - 返回一个数组.
   */
  parseResourceUrlAll(url = [], compressLevel = -1) {
    if (Array.isArray(url)) return url.map(item => this.parseResourceUrl(item, compressLevel))
    return []
  },
  /**
   * 处理富文本中的图片地址.
   * @author HuBin
   * @datetime 2022-03-10 16:15:00
   * @param {string} html - 富文本.
   * @returns {string} - 返回一个字符串.
   */
  // 将富文本内容中的图片src替换为跟随协议
  parseHtmlUrl() {
    var _this2 = this
    var html = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''

    var compressLevel = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : -1
    if (Array.isArray(html)) {
      html = html.join('<br>')
    }
    var matchReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/gi
    var srcReg = /[\'\"].+[\'\"]/
    if (!html || html.code) return //兼容1006敏感词问题
    if (typeof html === 'number') {
      html = '' + html
    }
    html = html.replace(/class="wscnph"/g, 'style="width: 100%; height: auto;"')
    // 取消富文本中图片的所有样式，并给图片只加上max-width: 100%;（胡彬 2021年12月21日）
    try {
      html = html.replace(/<img .+?\/?>/g, function(matchItem) {
        matchItem = matchItem.replace(/style=["'][^"']+?["']/g, '')
        matchItem = matchItem.replace(/<img/g, '<img style="max-width:100%;vertical-align: middle;" ')
        return matchItem
      })
    } catch (e) {}
    var match = html.match(matchReg)
    if (!match || !match.length) return html //匹配出src

    match.forEach(function(src) {
      html = html.replace(src, function(str) {
        str = src.replace(srcReg, function(r) {
          return '"' + _this2.parseResourceUrl(r.replace(/[\'\"]/g, ''), compressLevel) + '"'
        })
        return str
      })
    })
    return html
  },
  /**
   * 将对象生成查询字符串.
   * @author HuBin
   * @datetime 2022-03-10 16:15:00
   * @param {object} obj - 一个对象.
   * @returns {string} - 返回一个查询字符串.
   */
  qsStringify(obj) {
    let result = [] //用于存放所有键值对字符串
    let getType = function(o) {
      return Object.prototype.toString
        .call(o)
        .toLowerCase()
        .replace(/[\[\]]/g, '')
        .split(' ')[1]
    }
    if (getType(obj) !== 'object') {
      return ''
    }
    // 遍历数组或对象
    let traverse = function(o, lastKey = '') {
      if (getType(o) === 'object') {
        Object.keys(o).forEach(key => {
          let item = o[key]
          let subType = getType(item)
          if (['object', 'array'].includes(subType)) {
            let keyValue = lastKey ? `${lastKey}[${key}]` : `${key}`
            traverse(item, keyValue)
          } else {
            if (['undefined', 'null', 'function'].includes(subType)) {
              item = ''
            }
            let keyValue = lastKey
              ? `${lastKey}[${key}]=${encodeURIComponent(item)}`
              : `${key}=${encodeURIComponent(item)}`
            result.push(keyValue)
          }
        })
      }
      if (getType(o) === 'array') {
        o.forEach((item, index) => {
          let subType = getType(item)
          if (['object', 'array'].includes(subType)) {
            let keyValue = `${lastKey}[${index}]`
            traverse(item, keyValue)
          } else {
            if (['undefined', 'null', 'function'].includes(subType)) {
              item = ''
            }
            let keyValue = `${lastKey}[${index}]=${encodeURIComponent(item)}`
            result.push(keyValue)
          }
        })
      }
    }
    traverse(obj)
    return result.join('&')
  },
  /**
   * 将查询字符串解析为对象.
   * @author HuBin
   * @datetime 2022-03-10 16:15:00
   * @param {string} queryString - 一个查询字符串.
   * @returns {object} - 返回一个对象.
   */
  qsParse(queryString) {
    if (typeof queryString !== 'string') {
      return {}
    }
    let arr = queryString.match(/[^&=#?]+=[^&=#?]+/g)
    if (arr === null) {
      return {}
    }
    arr = arr.map(item => {
      return { key: item.split('=')[0], value: item.split('=')[1] }
    })
    // 重新组装数据
    let result = {}
    arr.forEach(item => {
      let { key, value } = item
      let allKeys = key.match(/[^\[\]]+/g)
      // 连续创建对象
      if (allKeys.length === 1) {
        // 存在一个key
        result[key] = decodeURIComponent(value)
      } else {
        // 递归创建对象或数组
        let lastValue = result // 存取上次递归得到的对象或数组
        let len = allKeys.length
        for (let i = 0; i < len - 1; i++) {
          let current = allKeys[i]
          let next = allKeys[i + 1]
          if (lastValue[current] === undefined) {
            lastValue[current] = isNaN(next) ? {} : []
            lastValue = lastValue[current]
          }
          if (lastValue[current]) {
            lastValue = lastValue[current]
          }
        }
        let lastKey = allKeys[len - 1]
        lastValue[lastKey] = decodeURIComponent(value)
      }
    })
    return result
  },
  /**
   * 将秒数转换为{a}天{b}时{c}分{d}秒.
   * @author HuBin
   * @datetime 2022-03-10 16:45:00
   * @param {number} num - 一个整数.
   * @returns {object} - 返回一个对象.
   */
  numberToCountdown(num, depth = 3) {
    let reg = /^\d+$/
    if (!reg.test(num)) {
      return {}
    }
    let minuteScale = 60
    let hourScale = 3600
    let dayScale = 86400
    let days = Math.floor(num / dayScale)
    let hours = Math.floor((num % dayScale) / hourScale)
    let minutes = Math.floor((num % hourScale) / minuteScale)
    let secs = num % minuteScale
    if (depth === 2) {
      return {
        minutes: (days * dayScale) / minuteScale + (hours * hourScale) / minuteScale + minutes,
        secs
      }
    }
    if (depth === 3) {
      return {
        hours: (days * dayScale) / hourScale + hours,
        minutes,
        secs
      }
    }
    return {
      days,
      hours,
      minutes,
      secs
    }
  },
  /**
   * 页面跳转函数.
   * @author HuBin
   * @datetime 2022年5月26日16:12:23
   * @param {string} url - 跳转链接地址.
   * @param {string} target - 可选值：“_blank”, “_self”.
   */
  jumpByLinkTag(url, target = '_self') {
    if (!url) {
      return
    }
    let aEl = document.createElement('a')
    aEl.target = target
    aEl.href = url
    aEl.click()
  },
  /**
   * 页面跳转函数.
   * @author HuBin
   * @datetime 2022年3月14日11:30:07
   * @param {string} url - 跳转地址.
   * @param {object} options - 配置项：{query: {}, delay: 1000,replace: true|false, target: _blank|_self}.
   * @returns {object} - 返回一个对象.
   */
  goTo(url, options = {}) {
    if (!url || typeof url !== 'string') {
      return
    }
    if (!this.isObject(options)) {
      return
    }
    let { query = {}, delay, replace, watch, target, openNew } = options
    delay = delay || 0
    //watch 监听 默认300
    if (watch) {
      delay = 300
    }
    let urlIncludeParams = this.qsParse(url)
    // 去掉参数中值为undefined的参数
    query = this.qsParse(this.qsStringify(query))
    let combineParams = { ...urlIncludeParams, ...query }
    let queryString = this.qsStringify(combineParams)
    let jumpUrl = url.split('?')[0] + (queryString ? '?' + queryString : '')
    // 打开新页面 保存sessionStorage

    // 全连接容灾跳转，链接处理
    let pcDomain = this.$store.state.globalConfig.pcDomain
    // 配置的之了课堂测试连接
    if (jumpUrl.includes('shenji.zlketang.com')) {
      let urlArr = jumpUrl.split('shenji.zlketang.com')
      urlArr.shift()
      jumpUrl = pcDomain + urlArr.join('')
    }
    // 配置的正式连接
    if (jumpUrl.includes('www.zlketang.com')) {
      let urlArr = jumpUrl.split('www.zlketang.com')
      urlArr.shift()
      jumpUrl = pcDomain + urlArr.join('')
    }
    if (openNew) {
      return window.open(jumpUrl)
    }
    // target === '_blank'时，表示新开标签页打开页面，只在PC端生效'
    // 打开新页面 不保存sessionStorage
    if (target === '_blank') {
      this.jumpByLinkTag(jumpUrl, target)
      return
    }
    if (replace) {
      setTimeout(() => {
        window.location.replace(jumpUrl)
      }, delay)
    } else {
      setTimeout(() => {
        window.location.href = jumpUrl
      }, delay)
    }
  },
  /**
   * 获取cookie.
   * @author HuBin
   * @datetime 2022年3月16日17:50:59
   * @param {string} key - 指定key.
   */
  getCookie(key) {
    let reg = new RegExp('s?' + key + '=([^;]+)(;|$)')
    let matchRes = document.cookie.match(reg)
    return matchRes ? matchRes[1] : ''
  },
  /**
   * 设置或删除cookie.
   * @author HuBin
   * @datetime 2022年3月16日17:50:59
   * @param {string} key - 指定key.
   * @param {string} value - 设置value.
   * @param {string} secs - 过期时间（单位：秒），默认过期时间为1天：secs = -1时，表示删除cookie.
   */
  setOrDeleteCookie(key, val, secs = 86400) {
    let nowMsecs = Date.now()
    let setMsecs = nowMsecs + secs * 1000
    var expireDate = new Date(setMsecs)
    document.cookie = key + '=' + val + ';path=/;expires=' + expireDate.toGMTString()
  },
  /**
   * 数组拆分成二维数组（从数组第一个元素开始），num代表拆分个数.
   * @author HuBin
   * @datetime 2022年6月1日21:19:38
   * @param {array} arr - 一个数组.
   * @param {number} num - 个数.
   */
  splitArray(arr, num = 1) {
    if (!Array.isArray(arr)) {
      return []
    }
    let newArr = arr.reduce((total, curr) => {
      let len = total.length
      if (len === 0) {
        total[len] = []
        total[len].push(curr)
        return total
      }
      if (total[len - 1].length < num) {
        total[len - 1].push(curr)
        return total
      }
      total[len] = []
      total[len].push(curr)
      return total
    }, [])
    return newArr
  },
  // 补充链接
  fixVideoSrc: function(url) {
    var protocol = location.protocol
    if (this.isUrl(url)) {
      return url.replace(/(http:|https:)/, protocol)
    }
    return url
  },
  //判断是否为url地址形式
  isUrl(url) {
    if (typeof url !== 'string') {
      return false
    }
    if (!(url.indexOf('http://') === 0 || url.indexOf('https://') === 0 || url.indexOf('//') > -1)) {
      return false
    }
    return true
  },
  // 判断是否在前端打开，因为某些组件服务器端渲染到浏览器端渲染会出问题，需要此组件中只在前端才加载
  isBrowser() {
    return typeof window === 'object'
  },
  // 去掉首位空格
  trim(s) {
    if (typeof s === 'string') {
      return s.replace(/(^\s+)|(\s+$)/g, '')
    }
    return ''
  },
  // 轮播图广告跳转
  advertisementJump(row, zlaData) {
    // 点击事件埋点
    if (zlaData) {
      let { type, name, content, ads_name, element_name, subject_id, profession_id } = zlaData
      if (type === 'click') {
        Vue.prototype.keyClick({
          key_name: name,
          key_content: content
        })
      }
      // 广告位埋点
      if (type === 'ad') {
        let attach = {}
        if (subject_id) {
          attach.subject_id = subject_id
        }
        if (profession_id) {
          attach.profession_id = profession_id
        }
        Vue.prototype.entryActivity({
          ads_name,
          element_name,
          attach
        })
      }
    }
    let { id, jump_extend, jump_style, jump_type, is_free } = row
    // jump_type：1-链接 2-商品 3-课程 4-权限集 5-客服 6-直播 7-会员
    jump_extend = typeof jump_extend === 'string' ? JSON.parse(jump_extend) : jump_extend || {}
    // let { jump_url, jump_live_id, jump_course_id } = jump_extend
    // if (+jump_type === 1) {
    //   //跳转链接
    //   // 如果是跳转pv域名 并且已经登陆，则带上登陆信息
    //   let query = {}
    //   if (jump_url.includes('pv.zlketang.com')) {
    //     let PAGERECORDER = this.getCookie('PAGERECORDER')
    //     query = { PAGERECORDER }
    //   }
    //   this.goTo(jump_url, {
    //     target: '_blank',
    //     query
    //   })
    //   return
    // }
    // if (+jump_type === 2) {
    //   let { jump_product_id } = jump_extend
    //   this.goTo(`/course_detail.html?product_id=${jump_product_id}`, { target: '_blank' })
    //   return
    // }
    // if (+jump_type === 3) {
    //   if (+is_free === 1) {
    //     //跳转免费看课页面
    //     this.goTo(`/vplay/free_course_play.html`, {
    //         target: '_blank',
    //         query: { course_id: jump_course_id }
    //       })
    //   } else {
    //     //跳转普通看课页面
    //     this.gotoPlay({ course_id: jump_course_id })
    //     // this.goTo(`/vplay/play.html`, { target: '_blank', query: { course_id: jump_course_id } })
    //   }
    //   // this.$message.warning('跳转课程暂未开通~')
    //   return
    // }
    // if (+jump_type === 4) {
    //   this.gotoPlay({ course_id: jump_course_id, web_auth_id: jump_web_auth_id })
    //   return
    // }
    if (+jump_type === 5) {
      //跳转客服
      this.show53Kefu()
      return
    }
    // if (+jump_type === 6) {
    //   this.goTo('/vcourse/live.html', {
    //     query: {
    //       live_id: jump_live_id
    //     },
    //     target: '_blank',
    //     watch: true
    //   })
    //   return
    // }
    if (+jump_type === 7) {
      // this.goTo(`/vplay/play.html`, { target: '_blank', query: { course_id: jump_course_id } })
      this.$message.warning('跳转会员暂未开通~')
      return
    }
    // this.$message.warning('无效的广告类型！')
  },
  // 处理后台配置的跳转数据
  handleJumpData(list) {
    return list.map(item => {
      let { child, id, jump_extend, object_url, jump_type, object_type, object_id, path, is_free } = item
      // jump_type：1-链接 2-商品 3-课程 4-权限集 5-客服 6-直播 7-会员
      jump_extend = typeof jump_extend === 'string' ? JSON.parse(jump_extend) : jump_extend || {}
      let { jump_url, jump_live_id, jump_course_id } = jump_extend
      if (child && child.length) {
        item.path = undefined
        item.child = this.handleJumpData(item.child)
      } else if (+object_type === 1) {
        item.path = path + `_detail/${object_id}.html`
      } else if (+object_type === 3) {
        item.path = object_url
      } else if (+jump_type === 1) {
        // 如果是跳转pv域名 并且已经登陆，则带上登陆信息
        let PAGERECORDER = ''
        if (typeof window === 'object' && jump_url.includes('pv.zlketang.com')) {
          PAGERECORDER = this.getCookie('PAGERECORDER')
        }
        item.path = PAGERECORDER ? `${jump_url}?PAGERECORDER=${PAGERECORDER}` : `${jump_url}`
      } else if (+jump_type === 2) {
        let { jump_product_id } = jump_extend
        item.path = `/course_detail.html?product_id=${jump_product_id}`
      } else if (+jump_type === 3) {
        let url = +is_free === 1 ? '/vplay/free_course_play.html' : '/vplay/play.html'
        item.path = `${url}?course_id=${jump_course_id}`
      } else if (+jump_type === 4) {
        let url = +is_free === 1 ? '/vplay/free_course_play.html' : '/vplay/play.html'
        item.path = `${url}?web_auth_id=${jump_course_id}`
      } else if (+jump_type === 6) {
        item.path = `/vcourse/live.html?live_id=${jump_live_id}`
      } else {
        item.path = undefined
      }
      return item
    })
  },
  //做题页面图片点击放大
  enlargePicture() {
    var htmlEle =
      '<div id="outerdiv" style="position:fixed;top:0;left:0;background:rgba(0,0,0,0.7);z-index:9999;width:100%;height:100%;display:none;">' +
      '  <div id="innerdiv" ' +
      '  style="position: absolute; left: 0; top: 0;right: 0; bottom: 0;text-align: center; margin: auto; transform: scale(1.5)">' +
      '  <img style="position: absolute; left: 0; top: 0;right: 0; bottom: 0;text-align: center; margin: auto;" id="bigimg" style="border:5px solid #fff;" src="" /></div>' +
      '</div> '
    // 放大倍数
    var sum = 1
    $('body').append(htmlEle)
    $(window).click(function(e) {
      if ($(e.target)[0].tagName.toLowerCase() == 'img' && $(e.target)[0].src.indexOf('/images/guanwangPic') == -1) {
        if (
          $(e.target).attr('class') &&
          $(e.target)
            .attr('class')
            .indexOf('no-large') != -1
        )
          return
        var _this = $(e.target) // 将当前的pimg元素作为_this传入函数
        if ($(e.target).attr('id') == 'bigimg') return
        imgShow('#outerdiv', '#innerdiv', '#bigimg', _this)
      }
    })
    function imgShow(outerdiv, innerdiv, bigimg, _this) {
      $(innerdiv).css('transform', 'scale(' + sum + ')')
      var src = _this.attr('src') // 获取当前点击的pimg元素中的src属性
      if (src.indexOf('//') == -1) return
      $(bigimg).attr('src', src) // 设置#bigimg元素的src属性
      $(outerdiv).fadeIn('fast') // 淡入显示#outerdiv及.pimg
      $(outerdiv).click(function() {
        // 再次点击淡出消失弹出层
        $(this).fadeOut('fast')
        $(document).unbind('mousewheel DOMMouseScroll') //移除事件
        sum = 1
      })
      try {
        $(document).on('mousewheel DOMMouseScroll', function(e) {
          var delta =
            (e.originalEvent.wheelDelta && (e.originalEvent.wheelDelta > 0 ? 1 : -1)) ||
            (e.originalEvent.detail && (e.originalEvent.detail > 0 ? -1 : 1))
          delta == 1 ? (sum += 0.05) : (sum -= 0.05)
          if (sum < 0 || sum > 6) return
          $(innerdiv).css('transform', 'scale(' + sum + ')')
        })
      } catch (error) {}
    }
  },
  deepCopyObject(obj) {
    // 深度拷贝对象
    if (Object.prototype.toString.call(obj) != '[object Object]') {
      return
    }
    var newObj = Object.create(null)
    for (var x in obj) {
      newObj[x] = obj[x]
    }
    return newObj
  },
  formatDateTime(obj) {
    /* dateObj是一个时间对象。
      配置：
      obj= {
        dateObj: new Date(),  // 一个日期对象（必选）
        mode: time|date, // mode值一旦设置成time，就是返回时分秒 12:00:00（优先级很高，决定输出的是日期还是时间）
        lang: 'ch', // 此字段为ch时，代表输出类似"2019年3月14日"日期
        separator: '分隔符', // 年月日之间的分割符，如（'-','/'）
        pad: true|false // 小于10的日期或时间是否需要补零
      }
    */
    if (Object.prototype.toString.call(obj) != '[object Object]') {
      return
    }

    // 补零方法
    function padZero(num) {
      if (Object.prototype.toString.call(num) != '[object Number]') {
        return
      }
      if (num < 10) {
        return '0' + num
      }
      return num + ''
    }
    // 返回值处理
    if (Object.prototype.toString.call(obj.dateObj) != '[object Date]') {
      return '不是日期对象'
    }

    var dateObj = obj.dateObj // 日期时间对象
    if (obj.mode == 'time') {
      var hour = obj.pad ? padZero(dateObj.getHours()) : dateObj.getHours()
      var min = obj.pad ? padZero(dateObj.getMinutes()) : dateObj.getMinutes()
      var sec = obj.pad ? padZero(dateObj.getSeconds()) : dateObj.getSeconds()
      return obj.lang != 'ch' ? hour + ':' + min + ':' + sec : hour + ' 时 ' + min + ' 分 ' + sec + ' 秒'
    }
    var year = dateObj.getFullYear()
    var month = obj.pad ? padZero(dateObj.getMonth() + 1) : dateObj.getMonth() + 1
    var date = obj.pad ? padZero(dateObj.getDate()) : dateObj.getDate()

    if (obj.lang == 'ch') {
      return year + ' 年 ' + month + ' 月 ' + date + ' 日'
    }
    if (obj.hasOwnProperty('separator')) {
      return year + obj.separator + month + obj.separator + date
    } else {
      return year + '-' + month + '-' + date
    }
  },
  /**
   * [isCompleteUrl 判断URL地址是否为完整路径]
   * @param  {[String]} url [待处理的url]
   * @return {[Boolean]}
   */
  isCompleteUrl(url) {
    if (typeof url !== 'string') {
      return false
    }
    if (/^\/\//.test(url) || url.indexOf('https:') > -1 || url.indexOf('http:') > -1) {
      return true
    }
    return false
  },
  // 显示登录弹窗
  showLoginDialog() {
    // 触发自定义的事件，去显示登录弹窗，事件监听在app.vue文件里
    const myEvent = new Event('showLoginDialog')
    window.document.dispatchEvent(myEvent)
    sessionStorage.setItem('lastUrl', location.href)
  },
  /**
   * [loadScript 动态加载js]
   * @param  {[String]}  url        [动态加载的script url]
   * @param  {Boolean} isAppendHead [是否append到head标签内]
   */
  loadScript(url, isAppendHead = false) {
    return this.loadResource(url, isAppendHead)
  },
  loadStyle(url) {
    return this.loadResource(url)
  },
  /**
   * [loadResource 动态加载js及css资源]
   * @param  {[String]}  url        [动态加载的url全路径]
   * @param  {Boolean} isAppendHead [是否append到head标签内,只支持js]
   * 实现逻辑：
   * 1、动态加载js和css，注意动态加载都是异步的，需要有回调
   * 2、默认第一次是直接加载url，加载失败后，会尝试替换成cdn的地址，再次加载
   * 3、加载成功会返回promise.then，多次尝试加载失败会
   */
  loadResource(url, isAppendHead = false) {
    if (typeof window === 'undefined') return
    //当前资源地址
    let currentUrl = url
    //备用域名地址数组
    const domainArr = ['image.zlketang.com', 'static.zlketang.com']
    //备用域名地址数组索引
    let domainIndex = 0
    //支持加载的扩展名数组
    const extensionArr = ['css', 'js']
    //获取url扩展名
    const fileExtension = url.substring(url.lastIndexOf('.') + 1)
    //获取当前域名函数
    const getCurrentDomain = domainUrl => {
      let domain = domainUrl.split('/') //以“/”进行分割
      return domain[2] ? domain[2] : ''
    }
    return new Promise((resolve, reject) => {
      //加载资源函数
      let loadAction = () => {
        //1.没有url地址 2.不支持的扩展名 3.获取当前域名返回为空 直接返回
        if (!currentUrl || !extensionArr.includes(fileExtension) || !getCurrentDomain(currentUrl)) return reject('fail')
        // 加载js文件
        if (fileExtension === 'js') {
          const scriptDom = document.createElement('script')
          scriptDom.setAttribute('src', currentUrl)
          scriptDom.setAttribute('forbid-global', true)
          scriptDom.setAttribute('type', 'text/javascript')
          document[isAppendHead ? 'head' : 'body'].appendChild(scriptDom)
          scriptDom.onload = () => {
            resolve('successful')
          }
          scriptDom.onerror = () => {
            //备用域名全部加载失败直接返回
            if (domainIndex >= domainArr.length) return reject('fail')
            document[isAppendHead ? 'head' : 'body'].removeChild(scriptDom)
            let currentDomain = getCurrentDomain(currentUrl)
            currentUrl = currentUrl.replace(currentDomain, domainArr[domainIndex])
            domainIndex++
            loadAction()
          }
        }
        //加载css文件
        if (fileExtension === 'css') {
          const linkDom = document.createElement('link')
          linkDom.setAttribute('href', currentUrl)
          linkDom.setAttribute('forbid-global', true)
          linkDom.setAttribute('type', 'text/css')
          linkDom.setAttribute('rel', 'stylesheet')
          document['head'].appendChild(linkDom)
          linkDom.onload = () => {
            resolve('successful')
          }
          linkDom.onerror = () => {
            //备用域名全部加载失败直接返回
            if (domainIndex >= domainArr.length) return reject('fail')
            document['head'].removeChild(linkDom)
            let currentDomain = getCurrentDomain(currentUrl)
            currentUrl = currentUrl.replace(currentDomain, domainArr[domainIndex])
            domainIndex++
            loadAction()
          }
        }
      }
      //开始加载
      loadAction()
    })
  },
  // 登出系统
  confirmLogOut() {
    this.$confirm('此操作将退出用户登陆?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {})
      .catch(() => {
        this.$message({
          type: 'info',
          message: '已取消退出'
        })
      })
  },
  // 获取参数
  getQuery(query) {
    if (typeof window === 'undefined') return {}
    var ret = {}
    var searchReg = /([^&=?]+)=([^&]+)/g
    var name, value
    let match = searchReg.exec(query)
    while (match) {
      name = match[1]
      value = match[2]
      ret[name] = decodeURIComponent(value)
      match = searchReg.exec(query)
    }
    return ret
  },
  /** 动态加载css样式
   * @param {string} url - css资源地址.
   * @param {string} id - css 标签id.
   * @return undifined
   */
  dynamicLoadCss(url, id) {
    let cssLoaded = document.getElementById(id)
    if (!cssLoaded) {
      let aliCss = document.createElement('link')
      aliCss.setAttribute('rel', 'stylesheet')
      aliCss.setAttribute('href', url)
      aliCss.setAttribute('id', id)
      document.head.appendChild(aliCss)
    }
  },
  /** 动态加载js样式
   * @param {string} url - js资源地址.
   * @param {string} id - js 标签id.
   * @param {function} callback -js加载完成执行的回调
   * @return undifined
   */
  dynamicLoadJs(url, id, callback) {
    let scriptLoaded = document.getElementById(id)
    if (scriptLoaded) {
      callback && Object.prototype.toString.call(callback).includes('Function') && callback()
      return
    }
    let aliScript = document.createElement('script')
    aliScript.setAttribute('src', url)
    aliScript.setAttribute('id', id)
    document.body.appendChild(aliScript)
    aliScript.onload = () => {
      callback && Object.prototype.toString.call(callback).includes('Function') && callback()
    }
  },
  isPC() {
    var userAgentInfo = navigator.userAgent
    var Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPod']
    var flag = true
    for (var v = 0; v < Agents.length; v++) {
      if (userAgentInfo.indexOf(Agents[v]) > 0) {
        flag = false
        break
      }
    }
    return flag
  },
  // 展示53客服
  show53Kefu() {
    window.open(
      '/dialog_1.htm',
      '',
      'height=499,width=712,top=0,left=0,toolbar=no,menubar=yes,scrollbars=yes,resizable=yes,location=no,status=no'
    )
  },
  timestampToHour(num, depth = 3) {
    let result = []
    let factor = [1, 60, 60 * 60, 24 * 60 * 60]

    num = num / 1000
    while (depth--) {
      let current = factor[depth]
      let remainder = parseInt(num / current, 10)
      result.push(remainder)
      num = num - remainder * current
    }
    return result.map(item => this.padZero(item)).join(':')
  },
  // js实现crc32方法
  crc32(str, crc) {
    var table =
      '00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D'
    if (crc === window.undefined) crc = 0
    var n = 0 //a number between 0 and 255
    var x = 0 //an hex number
    crc = crc ^ -1
    for (var i = 0, iTop = str.length; i < iTop; i++) {
      n = (crc ^ str.charCodeAt(i)) & 0xff
      x = '0x' + table.substr(n * 9, 8)
      crc = (crc >>> 8) ^ x
    }
    return crc ^ -1
  },
  // 跳转试听
  gotoAudition(item) {
    let url = '/vplay/freePlay.html'
    this.goTo(url, { query: item, target: '_blank' })
  },
  // 跳转看课页
  gotoPlay(item) {
    let url = '/vplay/play.html'
    this.goTo(url, { query: item, target: '_blank' })
  },
  // 动态插入canonical标签，对于通过传字符串传参的页面 利于seo统计权重时 统计到一个链接上
  addCanonical(url) {
    if (!this.isBrowser()) {
      return
    }
    let link = document.createElement('link')
    link.setAttribute('rel', 'canonical')
    link.setAttribute('href', url)
    var head = document.head || document.getElementsByTagName('head')[0]
    head.appendChild(link)
  },
  cloneDeep(obj) {
    if (!this.isObjectOrArray(obj)) return obj

    let result

    if (Array.isArray(obj)) {
      result = []

      obj.forEach(item => {
        result.push(this.cloneDeep(item))
      })
      return result
    }

    return this.ext({}, obj)
  },
  //是否是对象或数组
  isObjectOrArray(obj) {
    return Object.prototype.toString.call(obj).includes('Object') || Array.isArray(obj)
  },
  ext(target, source) {
    if (this.isObjectOrArray(source) && this.isObjectOrArray(target)) {
      for (let key in source) {
        let item = source[key]

        if (this.isObjectOrArray(item)) {
          if (this.isObject(item) && !this.isObject(target[key])) {
            target[key] = {}
          } else if (Array.isArray(item) && !Array.isArray(target[key])) {
            target[key] = []
          }

          this.ext(target[key], item)
        } else {
          target[key] = item
        }
      }
    }

    return target
  },
  /**
   * generateRandomString 生成随机字符串.
   * @author [Hu Bin]
   * @param {number} num - 生成位数，默认为6位.
   * @returns {string} - 返回一个num位字符串类型的随机字符创
   */
  generateRandomString(num = 6) {
    if (!/^\d+$/.test(num)) {
      num = 6
    }
    let alphabets = new Array(26).fill(null).map((v, i) => String.fromCharCode(97 + i))
    let numArr = new Array(10).fill(null).map((v, i) => i)
    let randomArr = [...alphabets, ...numArr]
    let firstChar = alphabets[Math.floor(Math.random() * 26)]
    let leftChars = new Array(num - 1).fill(null).map(() => {
      let randomIndex = Math.floor(Math.random() * randomArr.length)
      return randomArr[randomIndex]
    })
    leftChars.unshift(firstChar)
    return leftChars.join('')
  },
  // 判断直播是不是待更新时间状态
  isWaitStatus(row, isNeed = true) {
    if (!row) return false
    let { play_status_old, wait_status, play_status } = row
    if (!play_status_old) {
      play_status_old = play_status
    }
    if (+wait_status !== 1) return false
    if (!isNeed) return true
    if (+play_status_old === 0) {
      return true
    }
    return false
  },
  /**
   * @desc 时间格式化函数
   * @author hubin
   * @date 2021年6月27日
   * @example this.timeFormat('Y-m-d H:i:s', Date.now()/1000)
   * Y（年），m（补零的月份），d（补零的日期），H（补零的小时），i（补零的分钟），s（补零的秒），
   * M（不补零的月份），D（不补零的日期），h（不补零的小时），I（不补零的分钟），S（不补零的秒）
   */
  timeFormat(format, timestamp) {
    if (!(typeof format === 'string')) {
      return null
    }

    if (arguments.length < 2) {
      return null
    }

    if (!/^\d+$/.test(timestamp) && !/^\d+\.\d+$/.test(timestamp)) {
      return null
    }

    var milliSecs = timestamp * 1000
    var dateObj = new Date(milliSecs)
    var year = dateObj.getFullYear()
    var month = dateObj.getMonth() + 1
    var date = dateObj.getDate()
    var hour = dateObj.getHours()
    var min = dateObj.getMinutes()
    var sec = dateObj.getSeconds()
    var oDate = {
      year: year,
      month: month,
      date: date,
      hour: hour,
      min: min,
      sec: sec
    }

    var padZero = function padZero(num) {
      return num < 10 ? '0' + num : '' + num
    }

    var allKeys = 'month,date,hour,min,sec'
    allKeys.split(',').forEach(function(key) {
      oDate['fix' + key[0].toUpperCase() + key.slice(1)] = padZero(oDate[key])
    })
    var regArr = [
      {
        key: /Y/g,
        value: oDate.year
      },
      {
        key: /M/g,
        value: oDate.month
      },
      {
        key: /D/g,
        value: oDate.date
      },
      {
        key: /h/g,
        value: oDate.hour
      },
      {
        key: /I/g,
        value: oDate.min
      },
      {
        key: /S/g,
        value: oDate.sec
      },
      {
        key: /m/g,
        // 小于10，补零
        value: oDate.fixMonth
      },
      {
        key: /d/g,
        // 小于10，补零
        value: oDate.fixDate
      },
      {
        key: /H/g,
        // 小于10，补零
        value: oDate.fixHour
      },
      {
        key: /i/g,
        // 小于10，补零
        value: oDate.fixMin
      },
      {
        key: /s/g,
        // 小于10，补零
        value: oDate.fixSec
      }
    ]
    regArr.forEach(function(item) {
      var key = item.key,
        value = item.value
      format = format.replace(key, value)
    })
    return format
  },
  /* 
      滚动盒子触底加载通用方法
      el: 需要监听的盒子对象
       */
  initScroll(el, callback) {
    if (!el) {
      return
    }
    el.addEventListener(
      'scroll',
      function() {
        var distance = el.scrollHeight - el.offsetHeight - el.scrollTop
        if (distance < 10) {
          typeof callback === 'function' && callback()
        }
      },
      false
    )
  },
  /**
   * ajaxUpload 图文上传专用.
   * @author [Hu Bin]
   * @param {url} 接口地址
   * @returns {Promise} - 返回一个Promise
   */
  ajaxUpload(url, formData) {
    if (!url) {
      return Promise.reject('Invalid api')
    }
    if (Object.prototype.toString.call(formData) !== '[object FormData]') {
      return Promise.reject('Only support formdata type')
    }
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest()
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
          try {
            let res = JSON.parse(xhr.responseText)
            if (+res.errcode === 0) {
              resolve(res.data)
            } else {
              reject(res)
            }
          } catch (e) {
            reject('数据错误')
          }
        }
      }
      xhr.onerror = function() {
        return Promise.reject('网络错误')
      }
      xhr.open('POST', url, false)
      xhr.send(formData)
    })
  },
  /**
   * pick 返回对象指定key.
   * @author [Hu Bin]
   * @param {object} o 参考对象
   * @param {array} keysArr 指定key的数组
   * @returns {object} - 返回新对象
   */
  pick(o, keysArr = []) {
    let isObject = Object.prototype.toString.call(o) === '[object Object]'
    if (!isObject) return {}
    let pickObject = {}
    Array.isArray(keysArr) &&
      keysArr.forEach(key => {
        if (o.hasOwnProperty(key)) {
          pickObject[key] = o[key]
        }
      })
    return pickObject
  },
  // 禁用f12 和 鼠标右键
  forbidDebbugger() {
    // 禁用F12

    document.onkeydown = function() {
      if (window.event && window.event.keyCode == 123) {
        return false
      }
    }
    // 禁用右键
    document.oncontextmenu = function() {
      return false
    }
  },
  // 播放svga
  /**
   * @author [zj]
   * @param {object} dom 渲染 svg的元素
   * @param {object} options svga配置项
   * @returns {object} - undefined
   */
  // playSvga(dom,svga,options={}){
  //     var player = new SVGA.Player(dom);
  //     var parser = new SVGA.Parser(dom); // Must Provide same selector eg:#demoCanvas IF support IE6+
  //     parser.load(svga, function(videoItem) {
  //         player.setVideoItem(videoItem);
  //         player.startAnimation();
  //     })
  // },
  // 解决动态插入标签时，vue-loader无法打包问题
  fixTag(str) {
    return str.replace(/&lt;/g, '<').replace(/&gt;/g, '>')
  },
  // 注入标签
  injectTag(key, context) {
    if (extendTagConfig[key] && extendTagConfig[key].header) {
      context.extendCSS = this.fixTag(extendTagConfig[key].header)
    }
    if (extendTagConfig[key] && extendTagConfig[key].footer) {
      context.extendJS = this.fixTag(extendTagConfig[key].footer)
    }
  },
  // 显示接口访问频次弹窗
  showApiLimitDialog() {
    // 触发自定义的事件，去显示登录弹窗，事件监听在app.vue文件里
    const myEvent = new Event('showApiLimitDialog')
    window.document.dispatchEvent(myEvent)
  },
  // 全局设置ICP备案号
  setICPNumber() {
    let sites = [
      {
        site: 'zlketang.com',
        name: '成都环宇知了科技有限公司',
        number: '蜀ICP备16018498号-2',
        wangwen: '',
        gongan: {
          code: '川公网安备 51019002004410号',
          url: 'https://www.beian.gov.cn/portal/registerSystemInfo?recordcode=51019002004410'
        }
      },
      {
        site: 'zlketang.net',
        name: '成都环宇知了科技有限公司',
        number: '蜀ICP备16018498号-3',
        wangwen: '川网文【2018】4024-123号',
        gongan: {
          code: '川公网安备 51019002004409号',
          url: 'https://www.beian.gov.cn/portal/registerSystemInfo?recordcode=51019002004409'
        }
      },
      {
        site: 'zlketang.com.cn',
        name: '成都环宇知了科技有限公司',
        number: '蜀ICP备16018498号-4',
        wangwen: '川B2-20190681',
        gongan: {
          code: '川公网安备 51019002004408号 ',
          url: 'https://www.beian.gov.cn/portal/registerSystemInfo?recordcode=51019002004408'
        }
      },
      {
        site: 'fenwang100.cn',
        name: '成都多人行科技有限责任公司',
        number: '蜀ICP备20007379号-1',
        wangwen: '',
        gongan: {
          code: '',
          url: ''
        }
      },
      {
        site: `localhost:3002`,
        name: '成都环宇知了科技有限公司版权所有',
        number: '蜀ICP备16018498号-4',
        wangwen: '川B2-20190681',
        gongan: {
          code: '川公网安备 51019002004408号 ',
          url: 'https://www.beian.gov.cn/portal/registerSystemInfo?recordcode=51019002004408'
        }
      }
    ]
    let beianInfo =
      sites.find(item => {
        return location.host.endsWith(item.site)
      }) || {}

    let { number, wangwen, gongan = {}, name } = beianInfo
    this.site_num = number
    this.wangwen_num = wangwen
    this.gongan = gongan
    this.site_name = name
    this.year = new Date().getFullYear()
    this.host = location.host
    // 部分组件使用的是jQ（特别兼容）
    if (window.jQuery && window.$) {
      try {
        $('.site-year').html(this.year)
        $('.site-host').html(this.host)
        $('.beiNumber').html(this.site_num)
        $('.wangwen').html(this.wangwen_num)
        $('.site-name').html(this.site_name)
        $('.gongan')
          .html(this.gongan.code)
          .attr('href', this.gongan.url)
          .css({
            color: '#999999',
            'background-image':
              "url('')",
            'background-repeat': 'no-repeat',
            'background-position': 'left center',
            'padding-left': '21px',
            'background-size': 'contain'
          })
      } catch (e) {}
    }
  },
  // 判断做题答案
  computedStatus(answers = [], answer = [], isJuedgeHalf = false, selectCount = '') {
    // 选项存在个数限制时，若用户答案选项个数小于selectCount则直接判为错误
    if (
      this.isArray(answers) &&
      answers.length > 1 &&
      selectCount &&
      /^\d+$/.test(selectCount) &&
      answer.length &&
      answer.length < selectCount
    ) {
      return 'w'
    }
    //如果answer为空，则未答 数组中选项为空
    if (!answer.length || !answer.toString()) return 'n'
    //如果answer中含有answers没有的，则错误
    let findWrong =
      Array.isArray(answer) &&
      answer.filter(item => {
        return item && !answers.includes(item)
      })
    if (findWrong.length) return 'w'

    //判断全对
    if (answers.length === answer.length) {
      //看正确答案的每一项是不是都被选中
      let diff = Array.isArray(answers) && answers.filter(item => !answer.includes(item))
      return diff.length ? 'w' : 'r'
    }

    //判断半对
    return isJuedgeHalf ? 'h' : 'w'
  },

  //url域名处理
  urlDomainFormat(url) {
    if (!url) return ''
    // 这两个域名都是之了阿里云视频点播的域名，cdn有证书，vod没有证书
    // 为了省流 库里存的是vod,但官网不支持http,所以替换进行替换
    return url.replace('http://vod.zlketang.com', 'https://cdn.zlketang.com')
  },

  // seo补全路由链接
  parseFullPath(url) {
    if (!url) return ''
    if (this.getType(url) !== 'string') return ''
    if (url.indexOf('/') !== 0) {
      // //全连接时  替换当前域名
      let pcDomain = this.$store.state.globalConfig.pcDomain
      // 配置的之了课堂测试连接
      if (url.includes('shenji.zlketang.com')) {
        let urlArr = url.split('shenji.zlketang.com')
        urlArr.shift()
        url = pcDomain + urlArr.join('')
      }
      // 配置的正式连接
      if (url.includes('www.zlketang.com')) {
        let urlArr = url.split('www.zlketang.com')
        urlArr.shift()
        url = pcDomain + urlArr.join('')
      }
      return url
    }

    // 补/
    if (
      !(url.includes('?') || url.includes('&') || url.endsWith('/') || url.endsWith('.html') || url.endsWith('.htm'))
    ) {
      url = url + '/'
    }
    // 判断环境
    let { originalUrl } = this.$store.state
    if (originalUrl) {
      return originalUrl + url
    }
    return ''
  },
  // 加密转义字符串
  encodeString(obj) {
    return obj ? encodeURI(JSON.stringify(obj)) : null
  },
  // 解密parse字符串
  decodeString(str) {
    if (!str) return null
    try {
      return JSON.parse(decodeURI(str))
    } catch (error) {
      return null
    }
  },
  isIncludes(arr, val) {
    return arr.includes(val)
  },
  sleep(time) {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve()
      }, time)
    })
  },
  // 2023私教学习中心跳转看课做题  -----start------
  // 跳转直播
  goToLiveByStudy(item, defaultSubject) {
    let query = {
      live_id:
        item.task_items && Array.isArray(item.task_items) && item.task_items.length
          ? item.task_items[0].user_item.ref_id
          : ''
    }
    this.goTo('/vcourse/live.html', {
      query: query
    })
  },
  // 跳转录播
  goToVideoByStudy(item, defaultSubject) {
    let { user_item } =
      item.task_items && Array.isArray(item.task_items) && item.task_items.length ? item.task_items[0] : {}
    let query = {
      course_id: user_item.course_id,
      teacher_id: user_item.teacher_id,
      year: user_item.ref_info.year,
      course_section_id: user_item.course_section_id,
      isStudy: true,
      outline_id: item.outline_id
    }
    this.goTo('/vplay/play.html', {
      query,
      watch: true
    })
  },
  // 跳转作业
  goToWorkByStudy(item, defaultSubject) {
    let url = +defaultSubject.profession_id === 7 ? '/exam/cpa_exam.html' : '/exam/'
    let query = {
      exam_type: '8',
      paper_type: item.ref_info.paper_type,
      exam_id: item.ref_info.id,
      subject_id: defaultSubject.subject_id || '0',
      profession_id: defaultSubject.profession_id || '0',
      subject_power_id: defaultSubject.power_id || '0'
    }
    this.goTo(url, {
      query
    })
  },
  //
  /**
   *跳转去学习
   * @param {*} item 课程或者作业信息
   * @param {*} type type = course 课程跳转  work 作业跳转
   * @param {*} defaultSubject 默认专业信息
   * @param {*} lastStudyRecord  记录上次学习的请求方法
   */
  async jumpByStudy(item, type, defaultSubject, lastStudyRecord) {
    //记录最后一次学习任务
    let params = {
      power_id: defaultSubject.class_power_id,
      subject_id: defaultSubject.subject_id || '0',
      task_id: item.task_id,
      task_item_id: '',
      catalog_id: item.catalog_id || item.outline_catalog_id,
      outline_id: item.outline_id
    }
    if (type === 'course') {
      params.task_item_id =
        item.task_items && Array.isArray(item.task_items) && item.task_items.length ? item.task_items[0].id : ''
    } else {
      params.task_item_id = item.id
    }
    // 记录上次学习任务
    await lastStudyRecord(params)
    let mapFunc = {
      live: this.goToLiveByStudy, // 跳转直播
      back: this.goToVideoByStudy, // 跳转录播
      work: this.goToWorkByStudy // 作业
    }
    let currenTaskType = ''
    // 课程中 有直播和录播
    if (type === 'course') {
      let task_item =
        item.task_items && Array.isArray(item.task_items) && item.task_items.length ? item.task_items[0] : {}
      currenTaskType = +task_item.type === 2 ? 'live' : 'back'
    } else {
      currenTaskType = 'work'
    }
    // 需要使用apply改变this指向，否则引用的方法中的this指向变为其本身了
    mapFunc[currenTaskType].apply(this, [item, defaultSubject])
  },

  // 获取直播状态
  getLiveStatus(refInfo) {
    let { play_status, status, has_ref, vod_url } = refInfo
    // 引入的直播有问题
    if (!refInfo || !has_ref || +status === 0) {
      return {
        live_type: 5,
        label: '直播异常'
      }
    }
    switch (+play_status) {
      case 0:
        return {
          live_type: 0,
          label: '未开始'
        }
      case 1:
        return {
          live_type: 1,
          label: '直播中'
        }
      case 2:
        if (vod_url) {
          return {
            live_type: 2,
            label: '可回放'
          }
        } else {
          return {
            live_type: 3,
            label: '直播结束'
          }
        }
    }
  },
  // 显示视频时长
  getVideoTotal(item) {
    if(!item) return '-'
    let {
      watch_duration = 0, video_duration = 0
    } = item
    // 展示小时
    if (+video_duration >= 3600) {
      return (+watch_duration / 3600).toFixed(1) + '/' + (+video_duration / 3600).toFixed(1) + '小时'
    } else if (+video_duration >= 60 && +video_duration < 3600) {
      // 展示分钟
      return (+watch_duration / 60).toFixed(1) + '/' + (+video_duration / 60).toFixed(1) + '分钟'
    } else {
      // 展示秒
      return watch_duration + '/' + video_duration + '秒'
    }
  },
  // 看课统计
  getCoursePre(item) {
    if(!item) return '-'
    let {
      watch_duration = 0, video_duration = 0
    } = item
    return video_duration ?
      ((+watch_duration / +video_duration) * 100).toFixed(0) :
      '0'
  },
  // 获取直播的日期
  getLivedate(taskItem) {
    let { begin_time, end_time, play_status, vod_url } = taskItem.ref_info || {}
    switch (+play_status) {
      case 0:
        return begin_time ? this.dateFormat('m月d日 H:i', new Date(begin_time)) : '未知'
      case 1:
        return begin_time && end_time
          ? this.dateFormat('H:i', new Date(begin_time)) + '-' + this.dateFormat('H:i', new Date(end_time))
          : '未知'
      case 2:
        if (vod_url) {
          // 有回放
          return taskItem ? this.getVideoTotal(taskItem) : '未知'
        } else {
          // 无回放
          return begin_time ? this.dateFormat('m月d日 H:i', new Date(begin_time)) : '未知'
        }
    }
  },
  // 2023私教学习中心跳转看课做题  -----end------
  // 图片预览
  prevewImg(el, { transitionTime = 0.4, flyImgClass = '' } = {}, callback) {
    // 批量设置样式
    function setStyle(el, style) {
      for (let key in style) {
        el.style[key] = style[key]
      }
    }

    if (typeof el === 'string') {
      el = document.querySelector(el)
    }
    // 获取
    if (!el) return
    // 获取图片链接
    let imgUrl = el.getAttribute('src')
    if (!imgUrl) return
    // 保留原来的样式
    let { visibility } = el.style
    el.style.visibility = 'hidden'
    // 获取el的宽高
    let { width: width_old, height: height_old } = window.getComputedStyle(el)
    // 获取el在可视区的位置
    let { top, left } = el.getBoundingClientRect()
    // 获取可视区宽高
    let { clientHeight, clientWidth } = document.documentElement
    // 创建一个新的img
    let newImg = document.createElement('img')
    newImg.src = imgUrl
    let defaultClass = 'kl-prevew-img'
    newImg.className = flyImgClass ? defaultClass + '' + flyImgClass : defaultClass

    // 设置新的样式
    setStyle(newImg, {
      width: width_old,
      height: height_old,
      position: 'fixed',
      top: top + 'px',
      left: left + 'px',
      zIndex: 999,
      transition: `all ${transitionTime}s`,
      borderRadius: '5px',
      boxShadow: '0 0 5px #999',
      cursor: 'zoom-out',
      objectFit: 'cover'
    })

    // append到body
    document.body.appendChild(newImg)
    // 获取图片的真实宽高
    let img = new Image()
    img.src = imgUrl
    img.onload = () => {
      // 创建蒙层
      let mask = document.createElement('div')
      setStyle(mask, {
        position: 'fixed',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        zIndex: 998,
        background: 'rgba(0,0,0,0.5)',
        cursor: 'zoom-out',
        transition: `all ${transitionTime}s`
      })
      document.body.appendChild(mask)
      let { width, height } = img
      // 限制宽高不能超出可视区的95%，且图片不能变形，需要完整展示
      let maxWidth = clientWidth * 0.95
      let maxHeight = clientHeight * 0.95
      let ratio = width / height
      if (width > maxWidth) {
        width = maxWidth
        height = width / ratio
      }
      if (height > maxHeight) {
        height = maxHeight
        width = height * ratio
      }
      // 计算新的位置
      let newTop = (clientHeight - parseInt(height)) / 2
      let newLeft = (clientWidth - parseInt(width)) / 2

      // 设置新的位置
      setStyle(newImg, {
        top: newTop + 'px',
        left: newLeft + 'px',
        width: width + 'px',
        height: height + 'px'
      })

      // 防止重复触发
      let isFlag = false
      // 关闭预览相关方法
      let timer = setTimeout(() => {
        mask.addEventListener('click', closePrevew)
        newImg.addEventListener('click', closePrevew)
        // 鼠标滚轮事件触发也需要关闭
        document.addEventListener('mousewheel', closePrevew)
        document.addEventListener('DOMMouseScroll', closePrevew)
      }, transitionTime * 1000)

      function closePrevew() {
        if (isFlag) return
        isFlag = true
        // 使用动画移除蒙层及图片
        mask.style.opacity = 0
        // 图片要移动到原来的位置
        setStyle(newImg, {
          top: top + 'px',
          left: left + 'px',
          width: width_old,
          height: height_old,
          borderRadius: '5px',
          boxShadow: '0 0 5px #f0f0f0'
        })

        timer = setTimeout(() => {
          // 移除蒙层
          document.body.removeChild(mask)
          document.body.removeChild(newImg)
          // 图片显示
          el.style.visibility = visibility
          clearTimeout(timer)
          timer = null
          callback && callback()
        }, transitionTime * 1000)
      }
    }
  },
  createId() {
    return (
      'zl' +
      Math.random()
        .toString(36)
        .substr(2)
    )
  },
  _getRealCdnUrl(el, binding) {
    let bindValue = binding.value
    // 获取sourceUrl
    let sourceUrl = ''
    // 未采用懒加载情形
    if (!bindValue) {
      if (el.tagName === 'IMG') {
        // IMG标签取src
        sourceUrl = el.getAttribute('src')
      } else {
        // 其他标签取背景图
        let bgUrl = window.getComputedStyle(el, null).getPropertyValue('background-image')
        el.style.backgroundImage = ''

        if (bgUrl.includes('url(')) {
          bgUrl = bgUrl.match(/\(.+?\)/g)[0].replace(/['"()]/g, '')
        } else {
          bgUrl = ''
        }
        sourceUrl = bgUrl
      }
    } else {
      sourceUrl = bindValue
    }

    // 取不到路径，则不处理
    if (!sourceUrl) return ''
    // 自动调用parseResourceUrl
    sourceUrl = Vue.prototype.parseResourceUrl(sourceUrl)

    let a = document.createElement('a')
    a.href = sourceUrl
    let { pathname, host, protocol, search = '' } = a
    pathname = pathname.match(/.+?\.(png|jpeg|jpg|gif)/g)[0]
    // 去掉search中的/cq100w100
    search = search.replace(/\/cq\d{2,3}w\d{2,3}/g, '')
    let query = Vue.prototype.qsParse(search)
    // targetSourceUrl：最终渲染的图片地址
    let targetSourceUrl
    // 检测到链接的查询字符串存在x-image-process属性，并且值为“cq100w100”，则不转换了
    if (query['x-image-process'] && query['x-image-process'] === 'cq100w100') {
      // 得到处理后的图片路径，走原图逻辑，需要把“/cq100w100”去掉
      targetSourceUrl = sourceUrl.replace(/\/cq\d{2,3}w\d{2,3}/g, '')
    } else {
      query['x-image-process'] = 'cq100w100'
      search = Vue.prototype.qsStringify(query)
      search = search ? '?' + search : ''
      targetSourceUrl = `${protocol}//${host}${pathname}${search}`
    }
    return targetSourceUrl
  },
  /**
   * description 判断一个数组是否长度大于0
   * @param {Array} arr 需要判断的数组
   * @param {Boolean,String} message 是否提示信息
   */
  isArrayLength(arr, message = false) {
    let arrType = this.getType(arr)
    let messageType = this.getType(message)
    let isFlag = arrType === 'array' && arr.length > 0
    if (!isFlag) {
      if (message === true) {
        this.$message.warning.warning('请传入数组并且长度大于0!')
      } else if (messageType === 'string' && message) {
        this.$message.warning.warning(message)
      }
    }
    return isFlag
  },

  /**
   * description 判断是否可以转换为数字
   * @param {Object} obj 需要判断的对象
   * @param {Boolean,String} message 是否提示信息
   */
  isToNumber(obj, message = false) {
    let objType = this.getType(obj)
    let messageType = this.getType(message)
    let isFlag = objType === 'number' || (objType === 'string' && /^\d+$/.test(obj))
    if (!isFlag) {
      if (message === true) {
        this.$message.warning.warning('请传入数字或者可以转换为数字的字符串!')
      } else if (messageType === 'string' && message) {
        this.$message.warning.warning(message)
      }
    }
    return isFlag
      return targetSourceUrl
  },

  // 动态引用阿里播放器 - 10.25新增
  aLiVideoLoad() {
    // <script type="text/javascript" charset="utf-8" src="https://g.alicdn.com/de/prismplayer/2.9.13/aliplayer-min.js"></script>
    // <link rel="stylesheet" href="https://g.alicdn.com/de/prismplayer/2.9.13/skins/default/aliplayer-min.css" />
    return new Promise((resove, reject) => {
      const oScript = document.createElement('script')
      oScript.type = 'text/javascript'
      oScript.src = 'https://g.alicdn.com/de/prismplayer/2.9.13/aliplayer-min.js'
      document.body.appendChild(oScript)
      const oLink = document.createElement('link')
      oLink.rel = 'stylesheet'
      oLink.href = 'https://g.alicdn.com/de/prismplayer/2.9.13/skins/default/aliplayer-min.css'
      document.head.appendChild(oLink)
      oScript.onload = function() {
        resove()
      }
    })
  },
  klDateFormat(date, type = 'yyyy/M/d h:m:s') {
    // 传入的格式为string: yyyy/MM/dd hh:mm:ss  array: '[yyyy,MM,dd,hh,mm,ss]'
    // date 必须是标准时间戳 type为返回类型 string 或者 array
    const addZero = (num) => {
        return num < 10 ? '0' + num : num
    }
    let dateObj = new Date(date);
    let year = dateObj.getFullYear();
    let month = dateObj.getMonth() + 1;
    let day = dateObj.getDate();
    let hour = dateObj.getHours();
    let minute = dateObj.getMinutes();
    let second = dateObj.getSeconds();

    let yyyy = year;
    let MM = addZero(month);
    let M = month;
    let dd = addZero(day);
    let d = day;
    let hh = addZero(hour);
    let h = hour;
    let mm = addZero(minute);
    let m = minute;
    let ss = addZero(second);
    let s = second;

    if (type.includes("[") && type.includes("]")) {
        let arr = type.replace("[", "").replace("]", "").split(",");
        let result = [];
        arr.forEach(item => {
            result.push(eval(item));
        });
        return result;
    }
    // 将传入的参数分开
    let join_str = ''
    let arr = []
    if (type.includes(" ")) {
        arr = type.split(" ")
        join_str = ' '
    } else {
        arr.push(type)
    }
    let result = ''
    arr.forEach(item => {
        if (item.includes("/")) {
            let arr2 = item.split("/")
            arr2.forEach((item2, index) => {
                if (index == arr2.length - 1) {
                    result += eval(item2)
                } else {
                    result += eval(item2) + '/'
                }
            })
            result += join_str
        }
        if (item.includes("-")) {
            let arr2 = item.split("-")
            arr2.forEach((item2, index) => {
                if (index == arr2.length - 1) {
                    result += eval(item2)
                } else {
                    result += eval(item2) + '-'
                }
            })
            result += join_str
        }

        if (item.includes(":")) {
            let arr2 = item.split(":")
            arr2.forEach((item2, index) => {
                if (index == arr2.length - 1) {
                    result += eval(item2) 
                } else {
                    result += eval(item2) + ':'
                }
            })
        }
    })
    return result
},

updateQueryStringParameter(key, value) {
  let uri = window.location.href
  // 先去除末尾的&
  if (uri[uri.length - 1] === '&') {
    uri = uri.slice(0, uri.length - 1)
  }
  if (value === null) {
    let re = new RegExp('([?&])' + key + '=.*?(&|$)', 'i')
    uri = uri.replace(re, '$1')
    if (uri[uri.length - 1] === '?') {
      uri = uri.slice(0, uri.length - 1)
    }
    return uri
  }
  if (!value) {
    return uri
  }
  let re = new RegExp('([?&])' + key + '=.*?(&|$)', 'i')
  let separator = uri.indexOf('?') !== -1 ? '&' : '?'
  if (uri.match(re)) {
    return uri.replace(re, '$1' + key + '=' + value + '$2')
  } else {
    return uri + separator + key + '=' + value
  }
},
  createId() {
    return (
      'zl-' +
      Math.random()
        .toString(36)
        .substr(2)
    )
  },

  // 判断是否是爬虫
  isSpider(req) {
    let userAgent = req.headers['user-agent'] || ''
    // 根据请求userAgent判断当前是否为爬虫
    let spiderUserAgentList = ['www.baidu.com', 'www.so.com', 'www.sogou.com', 'www.bing.com', '360Spider']
    let spiderRedirectDoaminList = [
      'cp.zlketang.com',
      'shenji.zlketang.com',
      'cpm.zlketang.com',
      'shenjim.zlketang.com'
    ]

    // 是否包含搜索引擎名单,并且处于cs环境
    let currentHost = req.headers.host
    // 从搜索页面跳转过来
    let referer = req.headers.referer
    let isSpiderDoamin = spiderUserAgentList.some(item => userAgent.includes(item))
    let isSpiderRedirectDoamin = spiderRedirectDoaminList.some(
      item => (currentHost && currentHost.includes(item)) || (referer && referer.includes(item))
    )
    return isSpiderDoamin && isSpiderRedirectDoamin ? true : false
  },

updateUrl(key, value) {
  let newurl = this.updateQueryStringParameter(key, value);
  window.history.replaceState(
    {
      path: newurl,
    },
    "",
    newurl
  );
}


}

export default tool
